<template>
  <div class="user-house-device-logs">
    <el-table :data="pageData?.data">
      <el-table-column label="时间" width="180" prop="create_time" />

      <el-table-column prop="device_category" label="设备" width="150" />

      <el-table-column prop="类型" label="类型" width="150">
        <template #default="{ row }">
          {{ (row as DeviceLogModel).getDataTypeString() }}
        </template>
      </el-table-column>

      <el-table-column label="日志">
        <template #default="{ row }">
          <span :class="row.color">
            {{ (row as DeviceLogModel).getContentString() }}
          </span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { PageDataModel } from "@/model/page-data-model";
import { UserHouseDeviceLogsSearch } from "./avue-options";
import DeviceAPI from "@/api/device";
import { DeviceLogModel } from "@/model/device-log-model";

defineOptions({
  name: "UserHouseDeviceLogs",
});

const pollInterval = ref<number | null>(null); // 用于存储 setInterval 的 ID
const props = defineProps({
  userId: {
    type: [String, Number],
    default: "",
  },
  height: {
    type: String,
    default: "auto",
  },
  autoRefresh: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(["choosed"]);
const pageData = ref<PageDataModel<DeviceLogModel>>();
const loading = ref(false);
const search = ref<UserHouseDeviceLogsSearch>({
  user_id: props.userId,
  page: 1,
  page_size: 15,
});

onMounted(() => {
  handleQuery();

  if (props.autoRefresh) {
    startPolling(1000);
  }
});

onUnmounted(() => {
  stopPolling();
});

// 监听 autoRefresh 变化
watch(
  () => props.autoRefresh,
  (newValue) => {
    if (newValue) {
      startPolling(1000);
    } else {
      stopPolling();
    }
  }
);

// 查询
async function handleQuery() {
  loading.value = true;
  DeviceAPI.getDeviceLogByUserId(search.value)
    .then((res: PageDataModel<DeviceLogModel>) => {
      pageData.value = res;
      pageData.value.data = res.data.map((item) => new DeviceLogModel(item));
    })
    .finally(() => (loading.value = false));
}

/**
 * @description 启动轮询
 */
function startPolling(interval: number = 5000) {
  if (pollInterval.value === null) {
    pollInterval.value = window.setInterval(handleQuery, interval); // 每隔 interval 毫秒调用一次 fetchData
  }
}

/**
 * @description 停止轮询
 */
function stopPolling() {
  if (pollInterval.value !== null) {
    clearInterval(pollInterval.value);
    pollInterval.value = null;
  }
}
</script>

<style lang="scss" scoped>
.user-house-device-logs {
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  .info {
    color: #909399;
  }
  .danger {
    color: #f56c6c;
  }
  .warning {
    color: #e6a23c;
  }
  .success {
    color: #67c23a;
  }
  .primary {
    color: #409eff;
  }
}
</style>
